<template>
  <div class="container">
    <el-card
      shadow="always"
      :body-style="{ padding: '20px', 'min-height': '100vh' }"
    >
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-button type="primary" size="small" @click="download()"
            >导出数据</el-button
          >
          <el-button type="primary" size="small" @click="pack()"
            >打包所选问卷的文件</el-button
          >
        </el-col>
        <el-col :span="12" :offset="0"></el-col>
      </el-row>

      <el-divider direction="horizontal" content-position="left"></el-divider>

      <el-table :data="list" border @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="55"> </el-table-column>

        <el-table-column
          align="center"
          label="用户"
          prop="user"
        ></el-table-column>

        <el-table-column label="审核状态" align="center">
          <template slot-scope="{ row }">
            <el-tag
              type="info"
              size="mini"
              effect="dark"
              v-if="row.status == '未审核'"
              >{{ row.status }}</el-tag
            >
            <el-tag
              type="success"
              size="mini"
              effect="dark"
              v-if="row.status == '审核通过'"
              >{{ row.status }}</el-tag
            >
            <el-tag
              type="danger"
              size="mini"
              effect="dark"
              v-if="row.status == '审核不通过'"
              >{{ row.status }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column min-width="180px" align="center" label="提交时间">
          <template slot-scope="{ row }">{{
            new Date(row.create_time).toLocaleString()
          }}</template></el-table-column
        >
        <el-table-column
          :prop="item.id + ''"
          :key="item.id"
          align="center"
          :label="item.num + '.' + item.title.replace(/<.*?>/g, '')"
          v-for="item in columns"
          min-width="200px"
        >
          <template slot-scope="{ column, row }">
            <div v-if="row[column.property] && row[column.property].type == 3">
              <span
                v-for="(item1, index1) in row[column.property].options"
                :key="index1"
              >
                <span v-if="item1.value == row[column.property].answer"
                  >{{ item1.label }}
                  <span
                    style="border-bottom: 1px solid #000"
                    v-if="item1.type == 'other'"
                    >:{{ row[column.property].other }}</span
                  ></span
                >
              </span>
            </div>

            <div
              v-else-if="row[column.property] && row[column.property].type == 4"
            >
              <span
                v-for="(item1, index1) in row[column.property].options"
                :key="index1"
              >
                <span
                  v-if="row[column.property].answer.indexOf(item1.value) > -1"
                  >{{ item1.label
                  }}<span
                    style="border-bottom: 1px solid #000"
                    v-if="item1.type == 'other'"
                    >:{{ row[column.property].other }}</span
                  >,</span
                >
              </span>
            </div>

            <div
              v-else-if="row[column.property] && row[column.property].type == 6"
            >
              <span
                v-for="(item1, index1) in row[column.property].answer"
                :key="index1"
              >
                <el-image
                  :src="item1.url"
                  fit="fill"
                  :preview-src-list="
                    row[column.property].answer.map((i) => i.url)
                  "
                ></el-image>
              </span>
            </div>

            <div
              v-else-if="row[column.property] && row[column.property].type == 7"
            >
              <span>{{ row[column.property].answer.join("/") }}</span>
            </div>

            <div
              v-else-if="row[column.property] && row[column.property].type == 8"
            >
              <span
                v-for="(item1, index1) in row[column.property].answer"
                :key="index1"
              >
                <el-link
                  :underline="false"
                  type="primary"
                  style="cursor: pointer"
                  @click="previewUrl(item1.url)"
                  >{{ item1.name }}</el-link
                >
                <el-divider
                  class="undivider"
                  v-if="row[column.property].answer.length - 1 != index1"
                  direction="horizontal"
                  content-position="left"
                ></el-divider>
              </span>
            </div>

            <div
              v-else-if="row[column.property] && row[column.property].type == 9"
            >
              <el-image
                :src="row[column.property].answer"
                fit="fill"
                :preview-src-list="[row[column.property].answer]"
              ></el-image>
            </div>

            <div
              v-else-if="
                row[column.property] && row[column.property].type == 11
              "
            >
              <span>{{ row[column.property].answer.join("，") }}</span>
            </div>

            <span v-else>{{
              row[column.property] ? row[column.property].answer : null
            }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          fixed="right"
          label="操作"
          width="200px"
        >
          <template slot-scope="{ row }">
            <el-button
              type="danger"
              size="mini"
              @click="delSurveySubmit(row)"
              plain
              >删除</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="surveySubmitDetail(row)"
              plain
              >审核</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="详情"
      :visible.sync="detailVis"
      width="80%"
      top="10px"
      @close="
        detailVis = false;
        checkForm = {};
        previewClose();
      "
    >
      <el-form
        disabled
        :model="{ formList }"
        ref="form"
        label-width="0"
        size="small"
      >
        <item
          v-for="(item, index) in formList"
          :node="item"
          :index="index"
          :key="'item_' + index"
          :showmessage="true"
          @currentNode="() => {}"
          @deleteNode="() => {}"
          @Node="() => {}"
        ></item>
      </el-form>
      <span slot="footer">
        <el-select
          size="small"
          style="margin-right: 20px"
          v-model="checkForm.status"
          placeholder="请选择"
        >
          <el-option label="审核通过" value="审核通过"> </el-option>
          <el-option label="审核不通过" value="审核不通过"> </el-option>
        </el-select>
        <el-button size="small" type="primary" @click="check()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import item from "../edit/item.vue";
import {
  getSurveySubmit,
  getSurvey,
  delSurveySubmit,
  SurveySubmitCheck,
} from "@/api/form";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
export default {
  components: { ElImageViewer, item },
  data() {
    return {
      id: 25,
      list: [],
      previewList: [],
      formList: [],
      columns: [],
      t: 0,
      detailVis: false,
      selectList: [],
      checkForm: {},
    };
  },

  created() {
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.getSurveySubmit();
      getSurvey(this.id).then((res) => {
        this.columns = JSON.parse(res.text);
      });
    }
  },

  methods: {
    getSurveySubmit() {
      getSurveySubmit(this.id).then((res) => {
        this.list = res.map((i) => {
          let json = JSON.parse(i.text);
          let o = {};
          for (let j = 0; j < json.length; j++) {
            o[json[j].id] = json[j];
          }
          o.id = i.id;
          o.text = i.text;
          o.user = i.user;
          o.create_time = i.create_time;
          o.status = i.status;
          return o;
        });
      });
    },
    async download(id, submit_count) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      try {
        let list = await getSurveySubmit(this.id);
        let { text } = await getSurvey(this.id);
        let survey_data = JSON.parse(text);
        if (!list.length) {
          loading.close();
          this.$message.warning("没有已填写的问卷");
          return;
        }
        let filterVal = [];
        let answers = [];
        let header = [];
        for (let i = 0; i < list.length; i++) {
          answers.push(JSON.parse(list[i].text));
        }

        survey_data.map((i) => {
          header.push(i.num);
          filterVal.push(i.id);
        });

        import("@/vendor/Export2Excel").then((excel) => {
          const list = answers;
          const data = this.formatJson(filterVal, list);
          console.log(data);
          excel.export_json_to_excel({
            header: header,
            data,
            filename: "测试",
            autoWidth: true,
            bookType: "xlsx",
          });
          loading.close();
        });
      } catch (error) {
        loading.close();
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => {
        return filterVal.map((k) => {
          for (let l = 0; l < v.length; l++) {
            let j = v[l];
            if (k == j.id) {
              let a = JSON.stringify(j.answer)
                .replace("[", "")
                .replace("]", "")
                .replace(/\"/g, "");
              let text = null;
              if (j.other) {
                for (let x = 0; x < j.answer.length; x++) {
                  for (let y = 0; y < j.options.length; y++) {
                    if (
                      j.answer[x] == j.options[y].value &&
                      j.options[y].type &&
                      j.options[y].type == "other"
                    ) {
                      text = "  (" + j.other + ")";
                    }
                  }
                }

                for (let y = 0; y < j.options.length; y++) {
                  if (
                    j.answer == j.options[y].value &&
                    j.options[y].type &&
                    j.options[y].type == "other"
                  ) {
                    text = "  (" + j.other + ")";
                  }
                }
              }

              return a + (text ? text : "");
            } else if (l == v.length - 1) {
              return "";
            }
          }
        });
      });
    },
    delSurveySubmit(row) {
      delSurveySubmit(row.id).then((res) => {
        this.getSurveySubmit();
        this.$message.success("删除成功");
      });
    },
    surveySubmitDetail(data) {
      document.body.style.overflowY = "hidden";
      this.detailVis = true;
      this.formList = JSON.parse(data.text);
      this.checkForm.id = data.id;
    },
    previewClose() {
      document.body.style.overflowY = "auto";
    },
    previewUrl(url) {
      window.open(url);
    },
    handleSelectionChange(e) {
      let list = [];
      e.map((i) => {
        list.push(i.id);
      });
      this.selectList = list;
    },
    pack() {
      if (this.selectList.length == 0) {
        this.$notify({
          title: "提示",
          message: "请至少选择一份问卷",
          type: "warning",
          duration: "2000",
          position: "top-right",
          showClose: "true",
        });
        return;
      }
      let url =
        process.env.VUE_APP_BASE_API + "/pack/" + this.$route.query.id + "/";
      var form = document.createElement("form");
      form.id = "form";
      form.name = "form";
      form.enctype = "application/json";
      document.body.appendChild(form);
      var input = document.createElement("input");
      input.type = "hidden";
      input.name = "list";
      input.value = JSON.stringify(this.selectList);
      form.appendChild(input);
      form.method = "POST";
      form.action = url;
      form.submit();
      document.body.removeChild(form);
    },
    check() {
      this.detailVis = false;
      SurveySubmitCheck(this.checkForm)
        .then((res) => {
          this.getSurveySubmit()
          this.$notify({
            title: "提示",
            message: "审核成功",
            type: "success",
            duration: "2000",
            position: "top-right",
            showClose: "true",
          });
        })
        .catch((res) => {
          this.$notify({
            title: "提示",
            message: res.response.data.message,
            type: "error",
            duration: "2000",
            position: "top-right",
            showClose: "true",
          });
        });
    },
  },
};
</script>

<style scoped>
.el-image {
  width: 50px;
  height: 50px;
}
.container >>> .el-scrollbar__wrap {
  height: 100%;
  overflow-x: hidden;
}
.container >>> .is-horizontal {
  display: none;
}
.container >>> .el-form-item {
  cursor: default;
  border: none;
  padding: 0 13px;
  float: left;
  margin: 10px 0;
  position: relative;
}

.container >>> .el-form-item:hover {
  background: none;
}

.container >>> .el-col > .el-icon-delete {
  color: #f56c6c;
  position: absolute;
  right: 0;
  top: -10px;
  font-size: 22px;
  cursor: pointer;
  display: none;
}
.container >>> .el-dialog__body {
  overflow: auto;
  flex: 1;
}
.container >>> .el-dialog {
  display: flex;
  flex-direction: column;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  margin: 0 !important;
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}
.undivider {
  margin: 0;
}
</style>
